package com.suma.platform.core.util;

import java.util.concurrent.*;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

/**
 * @author suma
 * @date 2018/2/8 上午9:24
 */
public class PrintABCThread implements Runnable {

	private String name;
	private Object prev;
	private Object self;

	public PrintABCThread(String name, Object prev, Object self) {
		this.name = name;
		this.prev = prev;
		this.self = self;
	}

	@Override
	public void run() {
		int count = 0;
		while (count < 10) {
			synchronized (prev) {
				synchronized (self) {
					System.out.println(name);
					count++;
					self.notify();
				}
				try {
					if (count == 10) {
						prev.notify();
					} else {
						prev.wait();
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static void main(String[] args) throws Exception {
		Object a = new Object();
		Object b = new Object();
		Object c = new Object();
		PrintABCThread pa = new PrintABCThread("A", c, a);
		PrintABCThread pb = new PrintABCThread("B", a, b);
		PrintABCThread pc = new PrintABCThread("C", b, c);

//		new Thread(pa).start();
//		Thread.sleep(100); // 确保按顺序A、B、C执行
//		new Thread(pb).start();
//		Thread.sleep(100);
//		new Thread(pc).start();
//		Thread.sleep(100);

		ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("demo-pool").build();
		ExecutorService executorService = new ThreadPoolExecutor(10, 10, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(1024), threadFactory, new ThreadPoolExecutor.AbortPolicy());
		executorService.execute(pa);
		executorService.execute(pb);
		executorService.execute(pc);
	}
}
